const mqtt = require('mqtt');
require('../../global');
const fs=require('fs');
const path=require('path');
module.exports = class baseTask {
    constructor() {

        this.log= this._log();
        setTimeout(()=>{
            this.client = this.connectServer();

        },1000);
    }

    connectServer(){
        let clientId="Task" + ':Client:'+this.config.name+":"+Math.random().toString(16).substr(2, 8);
        this.config.clientId="Task" + ':Client:'+this.config.name;
        let serverHost=`mqtt://${this.config.taskServer.host}:${this.config.taskServer.port}`;
        let client = mqtt.connect(serverHost,{
            clientId: clientId
        });

        //订阅的主题
        let subscribes = [
            this.config.clientId
        ];

       client.on('connect', (connack)=> {
            log.info(`调度任务->${this.config.name} 连接服务端成功`);
            client.subscribe(subscribes, { qos: 1 }, (err)=> {
                if (err) {
                    log.error(`调度任务->${this.config.name} 订阅失败,${err}`);
                }
            });
            this.register();
            this.getMemory();
        });

       client.on('error', function(err) {
           log.error(`调度任务->${this.config.name} 发生错误,${err}`);
        });

        client.on('message', (topic, message, packet)=> {
            this.onMessage(topic, message, packet);
        });

        return client;

    }

    /**
     * 注册任务
     */
    register(){
        this.sendMsg("Task:Register",this.config);
    }

    async sendMsg(topic,data){
        return new  Promise((resolve, reject)=>{
            this.client.publish(topic, JSON.stringify(data), {qos:0}, function(err) {
                if(err){
                    reject(err);
                }else{
                    resolve();
                }
            });
        })
    }

    doStart(){
        this.start();
    }

    async doStop(){
        if(this.stop){
            await  this.stop();
        }
        process.exit();
    }

    async getMemory(){
        setTimeout(async ()=>{
            let memoryInfo=process.memoryUsage();
            let data={
                clientId:this.config.clientId,
                memoryInfo:memoryInfo
            };
            await this.sendMsg("Task:MemoryInfo",data);
            this.getMemory();
        },2000);
    }


    onMessage(topic, message, packet){

        let msg =JSON.parse(message.toString());  // message is Buffer

        switch (msg.type) {
            case "start":
                this.doStart();
                break;
            case "stop":
                this.stop();
                //client.end();
                break;
        }
    }



    _log(){
        let state=(str)=>{
            log.debug(str);
            let logStr=global.moment().format('YYYY-MM-DD HH:mm:ss') + " " + str+"\r\n";
            let logPath=path.join(this.taskPath,"/logs/state/"+global.moment().format('YYYY-MM-DD')+".log");
            fs.appendFileSync(logPath,logStr);
        };

        let error=(str)=>{
            let logStr=global.moment().format('YYYY-MM-DD HH:mm:ss') + " " + str+"\r\n";
            let logPath=path.join(this.taskPath,"/logs/error/"+global.moment().format('YYYY-MM-DD')+".log");
            fs.appendFileSync(logPath,logStr);
        };
        return{
            state:state,
            error:error
        }
    }



};


